// 认证相关工具
import { getToken, getUserInfo, setToken, setUserInfo, removeToken, removeUserInfo } from './storage.js'
import { PAGE_PATHS } from './constants.js'

// 检查是否已登录
export const isLoggedIn = () => {
  const token = getToken()
  const userInfo = getUserInfo()
  return !!(token && userInfo)
}

// 获取当前用户信息
export const getCurrentUser = () => {
  return getUserInfo()
}

// 获取当前Token
export const getCurrentToken = () => {
  return getToken()
}

// 保存用户登录信息
export const saveUserLoginInfo = (userInfo, token) => {
  setUserInfo(userInfo)
  setToken(token)
}

// 清除用户登录信息
export const clearUserLoginInfo = () => {
  removeUserInfo()
  removeToken()
}

// 检查登录状态，未登录则跳转到登录页
export const checkLoginAndRedirect = (redirectUrl = '') => {
  if (!isLoggedIn()) {
    const currentPages = getCurrentPages()
    const currentPage = currentPages[currentPages.length - 1]
    const currentRoute = currentPage.route
    
    // 如果当前不在登录页，则跳转到登录页
    if (currentRoute !== 'pages/login/login') {
      wx.navigateTo({
        url: `${PAGE_PATHS.LOGIN}${redirectUrl ? `?redirect=${encodeURIComponent(redirectUrl)}` : ''}`
      })
      return false
    }
  }
  return true
}

// 微信登录
export const wxLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (res) => {
        if (res.code) {
          resolve(res.code)
        } else {
          reject(new Error('获取微信登录code失败'))
        }
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

// 获取用户信息
export const getUserProfile = () => {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        resolve(res.userInfo)
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

// 检查微信授权状态
export const checkWxAuth = (scope) => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting[scope] === false) {
          // 用户拒绝授权
          reject(new Error('用户拒绝授权'))
        } else if (res.authSetting[scope] === undefined) {
          // 用户未授权
          reject(new Error('用户未授权'))
        } else {
          // 用户已授权
          resolve(true)
        }
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

// 请求微信授权
export const requestWxAuth = (scope) => {
  return new Promise((resolve, reject) => {
    wx.authorize({
      scope,
      success: () => {
        resolve(true)
      },
      fail: (error) => {
        if (error.errMsg.includes('auth deny')) {
          // 用户拒绝授权，引导用户手动开启
          wx.showModal({
            title: '授权提示',
            content: '需要您的授权才能使用此功能，请在设置中开启',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting[scope]) {
                      resolve(true)
                    } else {
                      reject(new Error('用户拒绝授权'))
                    }
                  },
                  fail: () => {
                    reject(new Error('打开设置失败'))
                  }
                })
              } else {
                reject(new Error('用户拒绝授权'))
              }
            }
          })
        } else {
          reject(error)
        }
      }
    })
  })
}

// 获取位置信息
export const getLocation = () => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        resolve({
          latitude: res.latitude,
          longitude: res.longitude,
          accuracy: res.accuracy
        })
      },
      fail: (error) => {
        if (error.errMsg.includes('auth deny')) {
          // 用户拒绝授权位置信息
          wx.showModal({
            title: '位置授权',
            content: '需要获取您的位置信息来提供更好的服务',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        }
        reject(error)
      }
    })
  })
}

// 获取系统信息
export const getSystemInfo = () => {
  return new Promise((resolve, reject) => {
    wx.getSystemInfo({
      success: (res) => {
        resolve(res)
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

// 检查网络状态
export const checkNetworkStatus = () => {
  return new Promise((resolve, reject) => {
    wx.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
          reject(new Error('网络连接不可用'))
        } else {
          resolve(res.networkType)
        }
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

// 监听网络状态变化
export const onNetworkStatusChange = (callback) => {
  wx.onNetworkStatusChange(callback)
}

// 显示网络错误提示
export const showNetworkError = () => {
  wx.showModal({
    title: '网络错误',
    content: '网络连接异常，请检查网络设置',
    showCancel: false,
    confirmText: '确定'
  })
}

export default {
  isLoggedIn,
  getCurrentUser,
  getCurrentToken,
  saveUserLoginInfo,
  clearUserLoginInfo,
  checkLoginAndRedirect,
  wxLogin,
  getUserProfile,
  checkWxAuth,
  requestWxAuth,
  getLocation,
  getSystemInfo,
  checkNetworkStatus,
  onNetworkStatusChange,
  showNetworkError
}
